package com.woniuxy.micromallserver.ordermag.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.common.bean.PageDto;
import com.woniuxy.micromallserver.bean.OrderBean;
import com.woniuxy.micromallserver.ordermag.mapper.OrderMapper;
import com.woniuxy.micromallserver.ordermag.service.IOrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author unreleased
 * @date 2021/1/25 18:57
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 按条件查询订单列表
     *
     * @param orderBean 携带查询参数的orderBean
     * @param pageNum   页码数
     * @param pageSize  每页条数
     * @return 分页PageDto
     */
    @Override
    public PageDto findOrderListByParams(OrderBean orderBean, Integer pageNum, Integer pageSize) {
        //页码非法则直接返回
        if(pageNum<=0){
            return null;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<OrderBean> data = orderMapper.findOrderListByParams(orderBean);
        PageInfo<OrderBean> pageInfo = new PageInfo<>(data);

        PageDto pageDto = new PageDto();
        pageDto.setTotal(pageInfo.getTotal());
        pageDto.setData(data);
        return pageDto;
    }

    /**
     * 查询本月销售额
     *
     * @return 金额
     */
    @Override
    public BigDecimal findCurrentMonthSales() {
        return orderMapper.findCurrentMonthSales();
    }

    /**
     * 根据参数修改订单
     *
     * @param orderBean 修改信息
     * @return 修改成功
     */
    @Override
    public boolean updateOrder(OrderBean orderBean) {
        return orderMapper.updateOrder(orderBean);
    }

    /**
     * 查询未发货订单数量
     *
     * @return 数量
     */
    @Override
    public int waitSendingOrderNums() {
        return orderMapper.waitSendingOrderNums();
    }

    @Override
    public boolean closeAllOrders(int[] ids) {
        System.out.println(orderMapper.closeAllOrders(ids));
        return orderMapper.closeAllOrders(ids)>0;
    }

    /**
     * 订单发货 更改订单状态
     *
     * @param deliveryId 物流单号
     * @param id         订单id
     * @return 是否更改成功
     */
    @Override
    public boolean updateDelivery(String deliveryId, Long id,String receiveTel) {
        if(orderMapper.updateDelivery(deliveryId,id)){
            //rabbitMQ异步发送短信
            Map<String,Object> data = new HashMap<>(2);
            data.put("deliveryId",deliveryId);
            data.put("tel",receiveTel);
            data.put("id", UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend("fanoutExchange","",data);
            return true;
        }else {
            return false;
        }
    }
}
